import Dexie, { type EntityTable } from "dexie";

export const db = new Dexie("appdb") as Dexie & {
  posts: EntityTable<Post, "id">;
  likes: EntityTable<Like, "userId">;
  replies: EntityTable<Reply, "id">;
};
db.version(2).stores({
  posts: "id, active, authorId",
  likes: "[postId+userId]",
  replies: "id, postId, authorId",
});

// 数据迁移：将旧的image字段转换为images数组
db.on("populate", () => {
  db.posts.toCollection().modify((post: any) => {
    if (typeof post.image === "string") {
      post.images = [post.image];
      delete post.image;
    } else if (!Array.isArray(post.images)) {
      post.images = [];
    }
  });
});
